<?php 
class Model{
	//保存链接信息
	public static $link = NULL;
	//保存表名
	protected $table = NULL;
	//初始化表信息
	private $opt;
	//保存发送的sql
	public static $sqls = array();

	public function __construct($table =  NULL){
		$this->table = is_null($table) ? C('DB_PREFIX').$this->table : C('DB_PREFIX').$table;
		$this->_connect();
		//初始化表信息
		$this->_opt();
	}

	/**
	 * [_connect 链接数据库]
	 * @return [type] [description]
	 */
	private function _connect(){
		if(is_null(self::$link)){
			$db = C('DB_DATABASE');
			if(empty($db)) halt('请先配置数据库');
			$link = new mysqli(C('DB_HOST'),C('DB_USER'),C('DB_PASSWORD'),$db,C('DB_PORT'));
			if($link->connect_error) halt('数据库链接错误，请检查配置项');
			$link->set_charset(C('DB_CHARSET'));
			self::$link = $link;
		}
	}

	/**
	 * [_opt 初始化表信息]
	 * @return [type] [description]
	 */
	private function _opt(){
		$this->opt = array(
			'field' => '*',
			'where' => '',
			'group' => '',
			'having' => '',
			'order' => '',
			'limit' => '',
		);
	}

	/**
	 * [query 查询方法]
	 * @param  [type] $sql [description]
	 * @return [type]      [description]
	 */
	public function query($sql){
		//保存sql语句
		self::$sqls[] = $sql;
		//将已经链接的信息赋值变量
		$link = self::$link;
		$result = $link->query($sql);
		if($link->errno) halt('mysql错误：'.$link->errno.'<br/>SQL:'.$sql);
		//保存查询的内容
		$rows = array();
		while ($row = $result->fetch_assoc()) {
			$rows[] = $row;
		}
		//释放结果集
		$result->free();
		$this->_opt();
		//返回数组
		return $rows;
	}

	/**
	 * [all 查询所有内容]
	 * @return [type] [description]
	 */
	public function all(){
		$sql = "SELECT ".$this->opt['field']." FROM ".$this->table.$this->opt['where'].$this->opt['group'].$this->opt['having'].$this->opt['order'].$this->opt['limit'];
		return $this->query($sql);
	}

	/**
	 * [field 查询给点字段内容]
	 * @param  [type] $field [字段名称（eg: "nikename"）]
	 * @return [type]        [description]
	 */
	public function field($field){
		$this->opt['field'] = $field;
		return $this;
	}

	/**
	 * 
	 * [where 条件查询]
	 * @param  [type] $where [条件]
	 * @return [type]        [description]
	 */
	public function where($where){
		$this->opt['where'] = " WHERE ".$where;
		return $this;
	}

	/**
	 * [order 排序]
	 * @param  [type] $order [排序条件]
	 * @return [type]        [description]
	 */
	public function order($order){
		$this->opt['order'] = " ORDER BY ".$where;
		return $this;
	}

	/**
	 * [limit 查询条数（分页），如果第二个参数不传，则从零开始查询]
	 * @param  [type] $limit [查询条数]
	 * @param  [type] $end   [不为空时，从第一个参数开始获取第二参数的条数]
	 * @return [type]        [description]
	 */
	public function limit($limit,$end = NULL){
		if(is_null($end)){
			$this->opt['limit'] = " LIMIT ".$limit;
		}else{
			$this->opt['limit'] = " LIMIT ".$limit.','.$end;
		}
		return $this;
	}

	/**
	 * [group 分组]
	 * @param  [type] $group [分组条件]
	 * @return [type]        [description]
	 */
	public function group($group){
		$this->opt['group'] = " GROUP BY ".$group;
		return $this;
	}

	/**
	 * [having 分组]
	 * @param  [type] $having [分组条件]
	 * @return [type]        [description]
	 */
	public function having($having){
		$this->opt['having'] = " HAVING ".$having;
		return $this;
	}

	/**
	 * [find 获取一条内容]
	 * @return [type] [description]
	 */
	public function find(){
		$data = $this->limit(1)->all();
		$data = current($data);
		return $data;
	}
	/**
	 * [one 获取一条内容]
	 * @return [type] [description]
	 */
	public function one(){
		return $this->find();
	}

	/**
	 * [findall 获取所有内容]
	 * @return [type] [description]
	 */
	public function findall(){
		return $this->all();
	}

	/**
	 * [exe 更新，添加]
	 * @param  [type] $sql [执行的sqk]
	 * @return [type]      [description]
	 */
	public function exe($sql){
		//保存sql语句
		self::$sqls[] = $sql;
		//将已经链接的信息赋值变量
		$link = self::$link;
		$bool = $link->query($sql);
		$this->_opt();
		if(is_object($bool)){
			halt('请用query方法发送查询sql');
		}
		if($bool){
			return $link->insert_id ? $link->insert_id : $link->affected_rows;
		}else{
			halt('mysql错误：'.$link->errno.'<br/>SQL:'.$sql);
		}
	}

	/**
	 * [delete 删除]
	 * @param  [type] $id    [可以为空，删除的条件]
	 * @param  [type] $field [字段名称]
	 * @return [type]        [description]
	 */
	public function delete($id = NULL,$field = NULL){
		if(is_null($id)){
			if(empty($this->opt['where'])) halt('删除语句必须有where条件');
			$sql = "DELETE FROM ".$this->table.$this->opt['where'];
			return $this->exe($sql);
		}else{
			if(is_null($field)) halt('需要删除的字段名称');
			$sql = "DELETE FROM ".$this->table." WHERE ".$field."='".$id."'";
			return $this->exe($sql);
		}
	}

	/**
	 * [_safe_str 安全处理方法]
	 * @param  [type] $str [字符串]
	 * @return [type]      [description]
	 */
	private function _safe_str($str){
		if(get_magic_quotes_gpc()){ //系统开启转义
			$str = stripcslashes($str); // 返转义回来
		}
		return self::$link->real_escape_string($str);
	}

	/**
	 * [add 添加方法]
	 * @param [type] $data [description]
	 */
	public function add($data = NULL){
		if(is_null($data)) $data = $_POST;
		$fields = "";
		$values = "";
		foreach ($data as $key => $value) {
			$fields .= "`".$this->_safe_str($key)."`";
			$values .= "'".$this->_safe_str($value)."'";
		}
		$fields = trim($fields,",");
		$values = trim($values,",");
		$sql = "INSERT INTO ".$this->table.'('.$fields.') VALUES ('.$values.')';
		//echo $sql;die;
		return $this->exe($sql);
	}

	/**
	 * [update 更新操作]
	 * @param  [type] $data [数组]
	 * @return [type]       [description]
	 */
	public function update($data = NULL){
		if(empty($this->opt['where'])) halt('更新语句必须有where条件');
		if(is_null($data)) $data = $_POST;
		$values = "";
		foreach ($data as $key => $value) {
			$values .= "`".$this->_safe_str($key)."`='".$this->_safe_str($value)."',";
		}
		$values = trim($values,",");
		$up_sql = "UPDATE ".$this->table." SET ".$values.$this->opt['where'];
		//echo $up_sql;die;
		return $this->exe($up_sql);
	}

	/**
	 * [save 更新操作]
	 * @param  [type] $data [数组]
	 * @return [type]       [description]
	 */
	public function save($data = NULL){
		return $this->update($data);
	}
}
?>